<template>
  <!-- 欧洲VAT递延统计 -->
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="is--card">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
        </XForm>
      </template>
      <template #toolbar_btns>
        <div class="w-full">
          <el-tabs v-model="activeName" @tab-change="handleStatusChange">
            <el-tab-pane
              :label="item.label"
              :name="item.value"
              v-for="item in optionsDataAll['out_has_tax']"
              :key="item.value"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <VActionBar :actions="actions" />
      </template>
      <template #tax_bill_url="{ row }">
        <el-button link type="primary" @click="handleLink(row.tax_bill_url)">
        </el-button>
      </template>

      <template #operation="{ row }">
        <el-button
          link
          type="primary"
          @click="handleDeclare(row)"
          v-hasPermi="[exportRebatesAuthList.vat_statistics.declare]"
        >
          {{ row?.is_declare ? "取消申报" : "申报" }}
        </el-button>
        <el-button
          link
          type="primary"
          @click="handleUploadFile(row)"
          v-hasPermi="[exportRebatesAuthList.vat_statistics.import]"
        >
          上传税金单
        </el-button>
      </template>
    </VTable>
    <ImportDialog ref="ImportDialogRef" @refresh="refresh" />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <Add
      v-model="addVisible"
      :ids="addIds"
      @close="addIds = []"
      @refresh="refresh"
    />
    <ComImportDialog ref="importDialogRef" @refresh="refresh" />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { exportRebatesAuthList } from "@/Auth/export-rebates.js";
// import ImportDialog from "./components/ImportDialog/index.vue";
import ImportDialog from "@/components/singleUpload/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { config_name } from "@/config/export.js";
import { useEnumSelect } from "@/hooks";
import { handleLink } from "@/hooks/tool.js";
import { vatDeclare, vatList } from "./api/index.js";
import { getTableSelectRow } from "@/hooks/tool.js";
import { logisticsList } from "@/api/index.js";
import Add from "./Add/index";
import ComImportDialog from "@/components/importDialog/index.vue";
import { fieldList } from "./data.js";

const { proxy } = getCurrentInstance();
const activeName = ref(0);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      tracking_number: "",
      package_number: "",
      logistics_id: [],
      dateRange: { type: "pick_up_date", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { title: "事业部", width: 260, field: "department_name" },
    { title: "物流商提货日期", width: 160, field: "pick_up_date" },
    { title: "头程备库单号", width: 200, field: "initial_backup_order_number" },
    { title: "自定义编号", width: 200, field: "custom_no" },
    { title: "包裹号", width: 200, field: "package_number" },
    { title: "追踪单号", width: 200, field: "tracking_number" },
    { title: "目的国", width: 100, field: "destination_country" },
    { title: "目的仓", width: 150, field: "warehouse" },
    { title: "责任人", width: 160, field: "wilfulness" },
    { title: "物流商", width: 200, field: "logistics_id_text" },
    { title: "渠道类型", width: 100, field: "channel_type_text" },
    { title: "是否包税", width: 100, field: "has_tax_text" },
    { title: "VAT进口商", width: 260, field: "vat_importer" },
    { title: "VAT税号", width: 160, field: "vat_tax" },
    { title: "进口申报日期", width: 160, field: "import_declaration_date" },
    { title: "币种", width: 100, field: "currency" },
    { title: "Duty金额", width: 160, field: "duty_amount" },
    { title: "VAT金额", width: 160, field: "vat_amount" },
    {
      title: "税金单",
      width: 160,
      field: "tax_bill_url",
      slots: { default: "tax_bill_url" },
    },
    { title: "采购总金额", width: 160, field: "total_purchases" },
    { title: "申报金额", width: 160, field: "declare_amount" },
    { title: "轨迹", width: 160, field: "track" },
    { title: "是否已申报", width: 160, field: "is_declare_text" },
    { title: "申报日期", width: 160, field: "declare_date" },
    {
      title: "操作",
      width: 180,
      field: "charge_amount",
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        form = {
          ...form,
          has_tax: activeName.value,
        };
        return vatList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const ImportDialogRef = ref();
const handleUploadFile = (item) => {
  ImportDialogRef.value.open({
    urlType: "/out/statistic-eur-vat-tax/upload-tax-bill",
  });
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const handleStatusChange = () => {
  nextTick(() => {
    refresh();
  });
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["export_rebates"]["statistic_eur_vat_tax"],
    condition,
  });
};
const { options: optionsData } = useEnumSelect({
  params: ["finance_settle_type", "finance_charge_status", "out_has_tax"],
});
const optionsData1 = ref({});
const getLogisticsList = async () => {
  const { data } = await logisticsList();
  optionsData1.value.logistics = data || [];
};
getLogisticsList();
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);
const handleDeclare = (item) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{item?.is_declare ? "取消申报" : "申报"}选中的
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await vatDeclare({
            id: item?.id,
            is_declare: item?.is_declare ? 0 : 1,
          });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const addVisible = ref(false);
//获取已选中的行
const getSelectRow = () => {
  // const getCheckboxRecords = tableRef?.value.tableRef.getCheckboxRecords();
  const getCheckboxRecords = tableRef.value?.$table.getCheckboxRecords();
  if (!getCheckboxRecords?.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return false;
  }
  const arr = getCheckboxRecords.map((e) => e.id);
  return arr;
};
const addIds = ref([]);
const handleAdd = () => {
  let ids = getSelectRow();
  if (!ids?.length) return;
  addIds.value = ids;
  addVisible.value = true;
};
const importDialogRef = ref();
const handleBatchTax = () => {
  importDialogRef.value?.open({
    type: "out.ouVatBillNos",
    urlType: "/out/statistic-eur-vat-tax/import-tax-bill-no",
  });
};
const actions = [
  {
    label: "添加VAT信息",
    fn: handleAdd,
    permission: [exportRebatesAuthList.vat_statistics.add],
  },
  {
    label: "批量上传税金单",
    fn: handleBatchTax,
    permission: [exportRebatesAuthList.vat_statistics.import],
  },
  {
    label: "导出",
    dkicon: "icon-Upload",
    right: true,
    fn: handleExport,
    permission: [exportRebatesAuthList.vat_statistics.export],
  },
];
</script>
